// cloudfunctions/toggleLike/index.js
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
  })
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { type, itemId, isLike,userInfo } = event;
    console.log(userInfo);
    if (!type || !itemId || typeof isLike !== 'boolean') {
      return { success: false, message: '参数错误' };
    }
    
    
    if (isLike) {
      // 点赞
      await db.collection('user_likes').add({
        data: {
          userId: userInfo._id,
          type,
          itemId,
          createTime: db.serverDate()
        }
      });
    } else {
      // 取消点赞
      await db.collection('user_likes')
        .where({
          userId: userInfo._id,
          type,
          itemId
        })
        .remove();
    }
    
    // 更新点赞数
    const collectionName = type === 'post' ? 'community_posts' : 'community_comments';
    await db.collection(collectionName).doc(itemId).update({
      data: {
        likeCount: isLike ? _.inc(1) : _.inc(-1)
      }
    });
    
    return {
      success: true,
      message: isLike ? '点赞成功' : '取消点赞成功'
    };
  } catch (error) {
    console.error('点赞操作失败', error);
    return {
      success: false,
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};